package com.tbox.tbsdk;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.fragment.app.FragmentActivity;

import com.lib.util.SPUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * Created by rui.yang
 * on 2020/10/29
 */
public class TBoxSDK {

    private volatile static TBoxSDK mInstance;
    private Context mContext;
    private String mMac;
    private static String tag = "tbsdk";

    private FrameUnpack frameUnpack = new FrameUnpack();

    private TBoxSDK(Context context) {
        this.mContext = context;
    }

    /**
     * Gets instance.
     *
     * @return the instance
     */
    public static TBoxSDK getInstance(Context context) {
        if (mInstance == null) {
            synchronized (TBoxSDK.class) {
                if (mInstance == null) {
                    mInstance = new TBoxSDK(context);
                }
            }
        }
        return mInstance;
    }

    DeviceScanningListener mScanningListener = null;
    /**
     * Start scan ble.
     *
     * @param activity the activity
     */
    public void startScanningDevice(String mac,Activity activity, DeviceScanningListener scanningListener) {
        mMac = mac.toUpperCase();
        this.mScanningListener = scanningListener;
        /**
         * 检查权限
         */
        RxPermissions rxPermissions = new RxPermissions((FragmentActivity) activity);
        rxPermissions
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(granted -> {
                    if (granted) { // Always true pre-M
                        // 用户已经同意该权限
                        scanDevice();
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        Log.e(tag, "蓝牙权限授权失败");
                        if (mScanningListener != null) {
                            mScanningListener.onDeviceScanningFailed(-1);
                        }
                    }
                });

    }

    private ArrayList<BluetoothDevice> bluetoothLeDevices = new ArrayList<>();

    private boolean addBluetoothDevice(BluetoothDevice bluetoothDevice) {
        Log.e("lander",bluetoothDevice.getAddress()+"  "+bluetoothDevice.getName());
//        for (BluetoothDevice bld : bluetoothLeDevices) {
//            if (bld.getAddress().equals(bluetoothDevice.getAddress())) {
//                return false;
//            }
//        }
        bluetoothLeDevices.clear();

        if (bluetoothDevice.getName() != null && bluetoothDevice.getName().equals("OTAServiceMgr")) {
            if(bluetoothDevice.getAddress().replaceAll(":","").equals(mMac)){
                SPUtils.getInstance().put(Constant.KEY_BT_OTA_MODEL,true);
            }
        }

        if (bluetoothDevice.getName() != null && bluetoothDevice.getName().toUpperCase().startsWith("MAGICYO")) {
            if(bluetoothDevice.getAddress().replaceAll(":","").equals(mMac)){
                bluetoothLeDevices.add(bluetoothDevice);
                Log.d(tag, "find BLE: " + bluetoothDevice.getName() + " " + bluetoothDevice.getAddress());
                if (mScanningListener != null) {
                    mScanningListener.onDeviceScanningListChanged(bluetoothLeDevices);
                }
                return true;
            }else{
                return false;
            }

        }
        return false;
    }

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mIsScanning = false;

    private final ScanCallback scanningCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            addBluetoothDevice(result.getDevice());
        }
    };

    private boolean scanDevice() {
        if (mIsScanning) {
            Log.d(tag, "ble is scanning now..");
            if (mScanningListener != null) {
                mScanningListener.onDeviceScanningFailed(-2);
            }
            return false;
        }

        // 初始化蓝牙适配器
        final BluetoothManager bluetoothManager =
                (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // 如果检测到蓝牙没有开启，尝试开启蓝牙
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            mContext.startActivity(enableBtIntent);
            Log.d(tag, "检测到蓝牙没有开启，尝试开启蓝牙");
            if (mScanningListener != null) {
                mScanningListener.onDeviceScanningFailed(-3);
            }
            return false;
        }

        mIsScanning = true;

        bluetoothLeDevices.clear();

        Log.d(tag, "start BLE scan..");

        mBluetoothAdapter.getBluetoothLeScanner().startScan(scanningCallback);

        return true;
    }

    /**
     * Stop scan ble boolean.
     *
     * @return the boolean
     */
    public boolean stopScanDevice() {
        if (!mIsScanning) {
            Log.d(tag, "BLE is stopped now..");
            return false;
        }

        Log.d(tag, "stop BLE scan..");
        mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanningCallback);

        mIsScanning = false;

        if (mScanningListener != null) {
            mScanningListener.onDeviceScanningStopped(bluetoothLeDevices);
            mScanningListener = null;
        }

        return true;
    }

    private BluetoothGatt mBluetoothGatt;

    private void closeBluetoothGatt(int errorCode) {
        if (mBluetoothGatt != null) {
            stopHeartbeat();
            stopRssiTimer();

            mBluetoothGatt.close();

            if (mConnectingListener != null) {
                if (errorCode > -1) {
                    mConnectingListener.onDeviceDisconnected(errorCode);
                } else {
                    mConnectingListener.onDeviceConnectFailed(errorCode);
                }
                mConnectingListener = null;
                frameUnpack.setConnectingListener(null);
            }

            mBluetoothGatt = null;
        }
    }

    DeviceConnectingListener mConnectingListener = null;
    /**
     * Connect ble boolean.
     *
     * @param bluetoothDevice the bluetooth device
     * @return the boolean
     */
    public boolean connectDevice(BluetoothDevice bluetoothDevice, DeviceConnectingListener connectingListener) {
        if (mBluetoothGatt != null) {
            Log.e(tag, "当前 BLE 处于拦截状态，请先断开连接");
            return false;
        }

        if (mIsScanning)  {
            stopScanDevice();
        }

        mConnectingListener = connectingListener;
        frameUnpack.setConnectingListener(connectingListener);

        bluetoothDevice.connectGatt(mContext, false, new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);

                mBluetoothGatt = gatt;

                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    Log.d(tag, "蓝牙连接成功");
                    // 协商单次发送最大值
                    requestMtu(64);
                } else {
                    Log.d(tag, "蓝牙连接已经断开");
                    closeBluetoothGatt(0);
                }
            }

            @Override
            public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                super.onReadRemoteRssi(gatt, rssi, status);
//                Log.d(tag, "信号强度变动：" + rssi + " status：" + status);

                if (status == BluetoothGatt.GATT_SUCCESS) {
                    if (mConnectingListener != null) {
                        mConnectingListener.onRssiUpdated(rssi);
                    }
                }
            }

            @Override
            public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
                super.onMtuChanged(gatt, mtu, status);

                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d(tag, "mtu 协商成功：" + mtu);
                    // 发现服务
                    mBluetoothGatt.discoverServices();
                } else {
                    Log.d(tag, "mtu 协商失败");
                    closeBluetoothGatt(-1);
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d(tag, "services discovered success");
                    List<BluetoothGattService> services = gatt.getServices();
                    Log.d("lanbin", "onServicesDiscovered有几个服务:"+services.size());
                    for (int i = 0; i <services.size() ; i++) {
                        List<BluetoothGattCharacteristic> characteristics = services.get(i).getCharacteristics();
                        Log.d("lanbin", "onServicesDiscovered服务"+i+"的特征数量："+characteristics.size()+ " "+services.get(i).getUuid());
                        for (int j = 0; j <characteristics.size() ; j++) {
                            if (characteristics.get(j).getUuid().toString().contains("ae10")){
//                                //  gatt.readCharacteristic(characteristics.get(j)); //读数据，跳到onCharacteristicRead
//                                byte[] value = {1, 2, 3, 4, 5, 6};
//                                characteristics.get(j).setValue(value);
//                                gatt.writeCharacteristic(characteristics.get(j)); //调到onCharacteristicWrite
                            }
                        }
                    }

                    // 绑定监听
                    bindNotify();
                } else {
                    Log.d(tag, "services discovered failed");
                    closeBluetoothGatt(-2);
                }
            }

            public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                Log.d(tag, "callback descriptor write status " + status
                        + " in thread " + Thread.currentThread());
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d(tag, "descriptor write success");
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            sendIdentificationData();
                        }
                    }, 200);
                } else {
                    Log.d(tag, "descriptor write failed");
                    closeBluetoothGatt(-3);
                }
            }

            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                                         int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d(tag, "read descriptor success: " + HexUtil.bytesToHexString(descriptor.getValue()));
                } else {
                    Log.d(tag, "read descriptor failed");
                }
            }

            public void onCharacteristicChanged(BluetoothGatt gatt,
                                                BluetoothGattCharacteristic characteristic) {
                Log.d(tag, "onCharacteristicChanged success: " + HexUtil.bytesToHexString(characteristic.getValue()));
                handleReceiveFrame(characteristic.getValue());
            }

            // 写入数据回调
            @Override
            public void onCharacteristicWrite(final BluetoothGatt gatt,
                                              final BluetoothGattCharacteristic characteristic,
                                              final int status) {
                Log.d(tag, "callback characteristic write status " + status
                        + " in thread " + Thread.currentThread());
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d(tag, "write value success: " + HexUtil.bytesToHexString(characteristic.getValue()));
                } else {
                    Log.d(tag, "write value failed");
                }
            }
        });
        return true;
    }

    public boolean disconnectDevice() {
        if (mBluetoothGatt == null) {
            Log.e(tag, "当前无设备连接");
            return false;
        }
        mBluetoothGatt.disconnect();
        return true;
    }

    DeviceControlListener mControlListener = null;

    /**
     * 解锁车辆.
     *
     * @param controlListener the control listener
     * @return the boolean
     */
    public boolean unlock(DeviceControlListener controlListener) {
        if (mBluetoothGatt == null) {
            return false;
        }
        this.mControlListener = controlListener;
        frameUnpack.setControlListener(controlListener);

        Log.e(tag, "发送解锁控制帧");
        sendMsg(FramePackage.packageUnlockFrame());
        return true;
    }

    /**
     * 上锁车辆.
     *
     * @param controlListener the control listener
     * @return the boolean
     */
    public boolean lock(DeviceControlListener controlListener) {
        if (mBluetoothGatt == null) {
            return false;
        }
        this.mControlListener = controlListener;
        frameUnpack.setControlListener(controlListener);

        Log.e(tag, "发送上锁控制帧");
        sendMsg(FramePackage.packageLockFrame());
        return true;
    }


    /**
     * 车辆上电
     *
     * @param controlListener the control listener
     * @return the boolean
     */
    public boolean powerOn(DeviceControlListener controlListener) {
        if (mBluetoothGatt == null) {
            return false;
        }
        this.mControlListener = controlListener;
        frameUnpack.setControlListener(controlListener);

        Log.e(tag, "发送解锁控制帧");
        sendMsg(FramePackage.packagePowerOnFrame());
        return true;
    }

    /**
     * 车辆下电.
     *
     * @param controlListener the control listener
     * @return the boolean
     */
    public boolean powerOff(DeviceControlListener controlListener) {
        if (mBluetoothGatt == null) {
            return false;
        }
        this.mControlListener = controlListener;
        frameUnpack.setControlListener(controlListener);

        Log.e(tag, "发送上锁控制帧");
        sendMsg(FramePackage.packagePowerOffFrame());
        return true;
    }



    /**
     * 寻车.
     *
     * @param controlListener the control listener
     * @return the boolean
     */
    public boolean lookFor(DeviceControlListener controlListener) {
        if (mBluetoothGatt == null) {
            return false;
        }
        this.mControlListener = controlListener;
        frameUnpack.setControlListener(controlListener);

        Log.e(tag, "发送寻车控制帧");
        sendMsg(FramePackage.packageLookForFrame());
        return true;
    }

    private void handleReceiveFrame(byte[] frame) {
        FrameUnpack.UnpackResult unpackResult = this.frameUnpack.unpackFrame(frame);
        if (unpackResult.authenticationFailed) {
            Log.e(tag, "鉴权失败，断开蓝牙");
            closeBluetoothGatt(-4);
            return;
        }

        if (unpackResult.replyFrame != null) {
            /// 需要发送确认帧 (ack、业务确认等)
            sendMsg(unpackResult.replyFrame);
        }
    }

    private void requestMtu(int mtu) {
        mBluetoothGatt.requestMtu(mtu);
    }


    public BluetoothGatt getBluetoothGatt(){
        return mBluetoothGatt;
    }

    public void swtichOta() {
        if (mBluetoothGatt == null) {
            return ;
        }

        BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("04263CF7-BF3C-22D1-CDEC-0003D5C4B51D"));
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("04263CF7-BF3C-10D1-CDEC-0003D5C4B51D"));
//        BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));
//        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("0000fff6-0000-1000-8000-00805F9B34FB"));
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                characteristic.setValue("456123");
                mBluetoothGatt.writeCharacteristic(characteristic);
            }
        });

    }

    private void bindNotify() {
        BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"));
        mBluetoothGatt.setCharacteristicNotification(characteristic, true);

        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }

    /// 发送鉴权帧
    private void sendIdentificationData() {
        byte[] frame = FramePackage.packageIdentificationFrame();
        sendMsg(frame);
        startHeartbeat();
        startRssiTimer();
    }

    /// 读取信号强度
    private Timer rssiTimer;
    private void stopRssiTimer() {
        if (rssiTimer != null) {
            Log.d(tag, "stop rssi timer");
            rssiTimer.cancel();
            rssiTimer = null;
        }
    }
    private void startRssiTimer() {
        stopRssiTimer();

        this.rssiTimer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (rssiTimer != null && mBluetoothGatt != null) {
                    mBluetoothGatt.readRemoteRssi();
                } else {
                    stopRssiTimer();
                }
            }
        };
        rssiTimer.schedule(task, 1000, 1000);
    }

    private Timer heartbeatTimer;
    private void stopHeartbeat() {
        if (heartbeatTimer != null) {
            Log.d(tag, "stop heartbeat");
            heartbeatTimer.cancel();
            heartbeatTimer = null;
        }
    }
    private void startHeartbeat() {
        stopHeartbeat();

        this.heartbeatTimer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (heartbeatTimer != null) {
                    Log.d(tag, "send heartbeat");
                    sendHeartbeat(FramePackage.packageHeartbeatFrame());
                }
            }
        };
        heartbeatTimer.schedule(task, 5000, 5000);
    }

    private Queue<byte[]> dataInfoQueue = new LinkedList<>();

    /**
     * Send msg.
     *
     * @param frame the frame
     */
    private boolean sendMsg(byte[] frame) {
        if (mBluetoothGatt == null) {
            Log.d(tag, "bluetooth is disconnect, refused to send");
            return false;
        }
        //往蓝牙数据通道的写入数据
        BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb"));

        if (dataInfoQueue != null) {
            dataInfoQueue.clear();
            dataInfoQueue = splitPacketFor64Bytes(frame);
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    send(characteristic);
                }
            });
        }
        return true;
    }

    //发送数据
    private void sendHeartbeat(byte[] frame) {
        if (mBluetoothGatt == null) {
            Log.d(tag, "bluetooth is disconnect, refused to send");
            return;
        }
        //往蓝牙数据通道的写入数据
        BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00001004-0000-1000-8000-00805f9b34fb"));

        if (dataInfoQueue != null) {
            dataInfoQueue.clear();
            dataInfoQueue = splitPacketFor64Bytes(frame);
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    send(characteristic);
                }
            });
        }
    }

    private void send(BluetoothGattCharacteristic characteristic) {
        if (dataInfoQueue != null && !dataInfoQueue.isEmpty()) {
            if (dataInfoQueue.peek() != null && characteristic != null) {
                characteristic.setValue(dataInfoQueue.poll());
                boolean resultSync = mBluetoothGatt.writeCharacteristic(characteristic);
                Log.d(tag, "write result sync: " + resultSync);
            }
            if (dataInfoQueue.peek() != null) {
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        send(characteristic);
                    }
                }, 200);
            }
        }
    }
    //数据分包
    private Queue<byte[]> splitPacketFor64Bytes(byte[] data) {
        int maxFrameLength = 64;
        Queue<byte[]> dataInfoQueue = new LinkedList<>();
        if (data != null) {
            int index = 0;
            do {
                byte[] surplusData = new byte[data.length - index];
                byte[] currentData;
                System.arraycopy(data, index, surplusData, 0, data.length - index);
                if (surplusData.length <= maxFrameLength) {
                    currentData = new byte[surplusData.length];
                    System.arraycopy(surplusData, 0, currentData, 0, surplusData.length);
                    index += surplusData.length;
                } else {
                    currentData = new byte[maxFrameLength];
                    System.arraycopy(data, index, currentData, 0, maxFrameLength);
                    index += maxFrameLength;
                }
                dataInfoQueue.offer(currentData);
            } while (index < data.length);
        }
        return dataInfoQueue;
    }


    /**
     * The interface T box device scanning listener.
     */
    public interface DeviceScanningListener {

        /**
         * 扫描失败
         *
         * @param code 错误码
         */
        void onDeviceScanningFailed(int code);

        /**
         * 设备列表扫描结果回调
         *
         * @param devices the devices
         */
        void onDeviceScanningListChanged(ArrayList<BluetoothDevice> devices);

        /**
         * 扫描停止
         *
         * @param devices the devices
         */
        void onDeviceScanningStopped(ArrayList<BluetoothDevice> devices);
    }

    /**
     * The interface T box device connecting listener.
     */
    public interface DeviceConnectingListener {
        /**
         * On device connected.
         *
         */
        void onDeviceConnected();

        /**
         * On device connect failed.
         * 鉴权失败等
         */
        void onDeviceConnectFailed(int errorCode);

        /**
         * On device disconnected.
         *
         */
        void onDeviceDisconnected(int errorCode);

        /**
         * 信号强度.
         *
         * @param rssi the rssi
         */
        void onRssiUpdated(int rssi);

        /**
         * 设备状态同步.
         *
         * @param lockStatus   the lock status
         * @param defendStatus the defend status
         * @param accStatus    the acc status
         */
        void onDeviceStatusSync(LockStatus lockStatus,
                                DefendStatus defendStatus,
                                ACCStatus accStatus);
    }

    public boolean getAccstatus(boolean accStatus){
        return  accStatus;
    }

    public interface DeviceControlListener {
        void onControlSuccess();
        void onControlFailed(int code);
    }

    /**
     * 锁状态枚举
     */
    public enum LockStatus {
        Unlocked(0x00),          // 开锁状态
        Locked(0x01),            // 锁定状态
        Standby(0x02),           // 待机
        NotInPlace(0x03),        // 没到位状态
        Fault(0x04),             // 故障状态
        NotSupported(0xFF),      // 锁不支持
        Undefined(-1);           // 未定义

        public int getStatus() {
            return status;
        }

        private int status;

        private LockStatus(int status) {
            this.status = status;
        }

        public static LockStatus of(int status) {
            for (LockStatus lockStatus : LockStatus.values()) {
                if (lockStatus.status == status) {
                    return lockStatus;
                }
            }
            Log.d(tag, "锁状态未定义：" + status);
            return LockStatus.Undefined;
        }
    }

    /**
     * 防护状态枚举.
     */
    public enum DefendStatus {
        On(0x01),          // 开启状态
        Off(0x02),         // 关闭状态
        Undefined(-1);     // 未定义

        public int getStatus() {
            return status;
        }

        private int status;

        private DefendStatus(int status) {
            this.status = status;
        }

        public static DefendStatus of(int status) {
            for (DefendStatus defendStatus : DefendStatus.values()) {
                if (defendStatus.status == status) {
                    return defendStatus;
                }
            }
            Log.d(tag, "防护状态未定义：" + status);
            return DefendStatus.Undefined;
        }
    }

    /**
     * ACC 状态枚举.
     */
    public enum ACCStatus {
        On(0x01),          // 开启状态
        Off(0x02),         // 关闭状态
        Undefined(-1);     // 未定义

        public int getStatus() {
            return status;
        }

        private int status;

        private ACCStatus(int status) {
            this.status = status;
        }

        public static ACCStatus of(int status) {
            for (ACCStatus tBoxDefendStatus : ACCStatus.values()) {
                if (tBoxDefendStatus.status == status) {
                    return tBoxDefendStatus;
                }
            }
            Log.d(tag, "ACC状态未定义：" + status);
            return ACCStatus.Undefined;
        }
    }
}
